package com.leetcode.根据数据结构分类.数组;

import java.util.Arrays;

/**
 * @author: xiaomi
 * @date: 2021/3/16
 * @description: 59. 螺旋矩阵 II
 * https://leetcode-cn.com/problems/spiral-matrix-ii/
 */
public class B_59_螺旋矩阵II {

    static B_59_螺旋矩阵II action =  new B_59_螺旋矩阵II();

    public static void main(String[] args) {
test1();
    }

    public static void test1() {
        int n = 3;
        int[][] res = action.generateMatrix(n);
        System.out.println("res = " + Arrays.toString(res));
    }


    /**
     * 根据 {@link B_54_螺旋矩阵)} 的思路，先根据轨迹画出二维数组，即可返回
     *
     * @param n
     * @return
     */
    public int[][] generateMatrix(int n) {
        int size = n * n;
        int upLimitIndex = 0, downLimitIndex = n - 1, leftLimitIndex = 0, rightLimitIndex = downLimitIndex;
//        int count = 0;
        int value = 1;
        int direction = 0;
        int[][] res = new int[n][n];
        while (value <= size) {
            switch (direction) {
                //向右
                case 0:
                    for (int i = leftLimitIndex; i <= rightLimitIndex; i++) {
                        res[upLimitIndex][i] = value++;
                    }
                    upLimitIndex++;
                    break;
                //向下
                case 1:
                    for (int i = upLimitIndex; i <= downLimitIndex; i++) {
                        res[i][rightLimitIndex] = value++;
                    }
                    rightLimitIndex--;
                    break;
                //向左
                case 2:
                    for (int i = rightLimitIndex; i >=leftLimitIndex; i--) {
                        res[downLimitIndex][i] = value++;
                    }
                    downLimitIndex--;
                    break;
                //向上
                case 3:
                    for (int i = downLimitIndex; i >=upLimitIndex; i--) {
                        res[i][leftLimitIndex] = value++;
                    }
                    leftLimitIndex++;
                    break;
            }

            if (direction == 3) {
                direction = 0;
            } else {
                direction++;
            }

        }
        return res;
    }
}
